package com.wallet.crypto.trustapp.ui.widget.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wallet.crypto.trustapp.R;
import com.wallet.crypto.trustapp.ui.widget.entity.CurrencyUnit;
import com.wallet.crypto.trustapp.ui.widget.holder.CurrencyUnitHolder;
import com.wallet.crypto.trustapp.util.IPreference;
import com.wallet.crypto.trustapp.util.Loger;
import com.wallet.crypto.trustapp.util.PreferenceImpl;
import java.util.ArrayList;

/**
 * Created by lingjianzhong on 2018/5/8.
 */

public class CurrencyUnitAdapter extends RecyclerView.Adapter<CurrencyUnitHolder> {

    ArrayList<CurrencyUnit> mItems;
    Context mContext;
    LayoutInflater mInflater;
    IPreference mIPreference;
    private int selectedPos = -1;//选择的位置

    public CurrencyUnitAdapter(Context context, ArrayList<CurrencyUnit> mItems) {
        this.mContext = context;
        this.mItems = mItems;
        this.mInflater = LayoutInflater.from(mContext);
        mIPreference = PreferenceImpl.getPreference(mContext);
        int pos = mIPreference.getInteger("Unit");
        if (pos == -1) {
            mItems.get(0).isSelect = true;
            selectedPos = 0;
        } else {
            mItems.get(pos).isSelect = true;
            selectedPos = pos;
        }
    }

    @NonNull
    @Override
    public CurrencyUnitHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.item_currency_unit_rev, parent, false);
        return new CurrencyUnitHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull CurrencyUnitHolder holder, int position) {
        holder.mTitle.setText(mItems.get(position).currency);
        if (mItems.get(position).isSelect()) {//选中效果
            holder.mHook.setVisibility(View.VISIBLE);
        } else {
            holder.mHook.setVisibility(View.INVISIBLE);
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Loger.e(" position " +position);
                if (selectedPos != position) {
                    mItems.get(selectedPos).isSelect = false;
                    notifyItemChanged(selectedPos);
                    selectedPos = position;
                    mItems.get(selectedPos).isSelect = true;
                    mIPreference.put("Unit", selectedPos);
                    notifyItemChanged(selectedPos);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

}
